package org.jeecg.modules.kuner.realnameauthbase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.kuner.realnameauthbase.entity.KrRealNameAuthBase;
import org.jeecg.modules.kuner.realnameauthbase.mapper.KrRealNameAuthBaseMapper;
import org.jeecg.modules.kuner.realnameauthbase.service.IKrRealNameAuthBaseService;
import org.jeecg.modules.kuner.realnameauthbase.vo.RealNameAuthBaseVO;
import org.jeecg.modules.putil.LoginUserUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @Description: 实名认证
 * @Author: jeecg-boot
 * @Date: 2025-02-17
 * @Version: V1.0
 */
@Service
public class KrRealNameAuthBaseServiceImpl extends ServiceImpl<KrRealNameAuthBaseMapper, KrRealNameAuthBase> implements IKrRealNameAuthBaseService {

    @Resource
    private LoginUserUtil loginUserUtil;

    /**
     * 进行实名认证校验
     */
    @Override
    public void realNameAuthChecker() {
        LoginUser loginUser = loginUserUtil.getLoginUser();
        if (getPassAuthByUserId(loginUser.getId()) == null) {
            throw new JeecgBootException("用户未实名！");
        }

    }

    /**
     * 提交实名认证
     *
     * @param realNameAuthBaseVO 提交认证必要参数信息
     */
    @Override
    public void submitRealName(RealNameAuthBaseVO realNameAuthBaseVO) {
        submitRealNameChecker(realNameAuthBaseVO.getUserId());
        save(realNameAuthBaseVO.buildPojo());
    }

    /**
     * 提交实名认证申请
     *
     * @param userId 用户ID
     */
    @Override
    public void submitRealNameChecker(String userId) {
        Optional<KrRealNameAuthBase> any = list(new LambdaQueryWrapper<KrRealNameAuthBase>()
                .eq(KrRealNameAuthBase::getUserId, userId)
                .ne(KrRealNameAuthBase::getJudgeStatus, CommonConstant.JUDGE_OBJECTION)
        ).stream().findAny();
        if (any.isPresent()) {
            throw new JeecgBootException("您已经提交了审核，请等待审核结果！");
        }
    }

    /**
     * 我的实名信息
     *
     * @return 查询到的我的实名信息
     */
    @Override
    public KrRealNameAuthBase myRealnameInfo() {
        return getPassAuthByUserId(loginUserUtil.getLoginUser().getId());
    }

    /**
     * 查询根据用户ID
     *
     * @param userId 用户ID
     * @return 查询出来的List
     */
    public List<KrRealNameAuthBase> getByUserId(String userId) {
        return list(new LambdaQueryWrapper<KrRealNameAuthBase>().eq(KrRealNameAuthBase::getUserId, userId));
    }

    /**
     * 根据用户ID查询是否审核通过
     *
     * @param userId 用户ID
     * @return 查询到的结果
     */
    public KrRealNameAuthBase getPassAuthByUserId(String userId) {
        return this.getBaseMapper().selectPassAuthByUserId(userId);
    }
}
